<template>
	<view>
		<view class="head">
			<view @click="caidan"   class="headImg animated " hover-start-time="100" hover-stay-time="1000"  hover-class="rubberBand">
					<view>
					<image style="image{will-change: transform};" @tap="changeImage"  :src="headImgURL"></image>	
					</view>
			</view>
			<view class="hearText">
				<view>{{username}}</view>
				<view >
					<text style="font-size: 25rpx;" v-if="userRight.alias==='养殖户'" class="icon iconfont">&#xe69c;</text>
					<text style="font-size: 40rpx;" v-if="userRight.alias==='政府人员'" class="icon iconfont">&#xe62c;</text>
					<text>{{userRight.alias}}</text>
					</view>
			</view>
		</view>
		<view style="height: 450rpx;"></view>
		
	 <view class="setListModel">
		 <view class="setList">
			<view v-if="userRight.name=='livestock'" @tap="toMyScan()" class="setListLi bor"><image src="../../static/set/QR.png"></image><text>我的二维码</text></view>
			<view v-if="userRight.name=='livestock'"  @tap="toEpidemicReport()" class="setListLi bor"><image src="../../static/set/shangbao.png"></image><text>疫情上报</text></view>
			<view v-if="userRight.name=='government'"  @tap="goTianBao()" class="setListLi bor"><image src="../../static/set/tianbao.png"></image><text>养殖信息填报</text></view>
			<view v-if="userRight.name=='government'"  @tap="goTongJi()" class="setListLi bor"><image src="../../static/set/tongji.png"></image><text>智能统计</text></view>
			<view v-if="false"  @tap="toInviteEmployees()" class="setListLi bor"><image src="../../static/set/yaoqing.png"></image><text>邀请员工</text></view>
			<view v-if="false" @tap="toGrading()" class="setListLi bor"><image src="../../static/set/shenhe.png"></image><text>员工审核</text></view>
			<view @tap="modifyPassword" class="setListLi bor"><image src="../../static/set/xiugaimima.png"></image><text>修改密码</text></view>
			<view @tap="clear" class="setListLi "><image src="../../static/set/clear.png"></image><text>清除缓存</text></view>
		</view>
	 </view>
	 
	 <view class="setListModel top">
	 		 <view class="setList">
	 			 <view @tap='update()' class="setListLi bor"><image src="../../static/set/gengxin.png"></image><text>检查更新</text><view v-show="up"></view></view>
	 			 <view @tap='logout()' class="setListLi"><image src="../../static/set/outLogin.png"></image><text>退出登录</text></view>
	 		</view>
	 </view>
	 <!-- 更新提示 -->
	 <view v-if="isShow" @touchmove.stop.prevent="moveHandle" class="sendModel" >
	 	<view class="updateModel">
			<view class="title">{{upTitle}}</view>
			<view class="box">
				<view class="content">
					<scroll-view class="scroll" scroll-y="true"> 
					   {{updataContent}}
					</scroll-view>
				</view>
				<view v-show="disabled" class="downSize">预计下载大小：<text>{{totalBytesExpectedToWrite}}</text></view>
				<view class="progress">
					<view class="realTime">
						<view :style="'width:'+progress+'%'" class="real"></view>
					</view>
					<view class="percent">{{progress}}%</view>
				</view>
				<view class="butModel">
					<button @tap="cancelDown()" type="default" class="cancelBut">取消</button>
					<button :disabled="disabled" @tap="download()" type="primary" class="cancelBut">下载</button>
				</view>
			</view>
		</view>
	 </view>
	</view>
</template>
<script>
	import User from "../../common/user.js"
	export default {
		data() {
			return {
				username:'',
				userRight:'',
				updataUrl:'',
				totalBytesExpectedToWrite:'',//预期需要下载的数据总长度，单位 Bytes
				progress:0,//	下载进度百分比
				totalBytesWritten:'',//已经下载的数据长度，单位 Bytes
				imgList:[],
				headImgURL:"",
				isShow:false,
				cancel:false,
				upTitle:"",
				updataContent:"",
				disabled:false,
				version:'',
				img:"",
				up:false
			};
		},
		onShow(){
			this.up = this.system.updated;
		},
		onReady() {
			this.username=this.User.userInfo.user_name;
			this.userRight=this.User.userRight;
			this.getImg();
			console.log(this.User)
		},
		methods:{
			//政府记录填报信息
			goTianBao () {
				let Right = this.User.userRight.name;
				if(Right=="government"){
					console.log(22)
					uni.navigateTo({
						url: '../statistics/farmer_information'
					})
				}
				else{
					console.log(11)
					uni.showToast({
						title:"您没有访问权限！",
						icon:"none"
					})
				}
			},
			//智能统计
			goTongJi () {
				let Right = this.User.userRight.name;
				if(Right!="government"){
					console.log(11)
					uni.showToast({
						title:"您没有访问权限！",
						icon:"none"
					})
				}
				else if(Right=="government"){
						console.log(22)
					uni.navigateTo({
					url: '../statistics/city'
				})
				}
				
			},
			//取消下载
			cancelDown(){
				uni.showModal({
					title:"提示",
					content:"您确定要取消更新？",
					success: (res) => {
						if(res.confirm){
							this.progress = 0;
							this.disabled = false;
							this.cancel = true;
							this.isShow = false;
						}
						else if(res.cancel){
							this.cancel = false;
						}
					}
				})
			},
			caidan(){
				uni.vibrateShort();
			},
			//头像缓存
			getImg(){
				this.headImgURL = uni.getStorageSync('headImg'+this.User.userInfo.id);
				// if(this.headImgURL==this.User.userInfo.userHead){return;};
				uni.downloadFile({
				    url: this.User.userInfo.userHead, //仅为示例，并非真实的资源
				    success: (res) => {
						// console.log(res)
						uni.saveFile({
						     tempFilePath:res.tempFilePath,
						     success:(data)=>{
							 uni.setStorageSync('headImg'+this.User.userInfo.id,data.savedFilePath);
							 this.headImgURL = uni.getStorageSync('headImg'+this.User.userInfo.id);
						     }
						   });
				    }
				});
				
			},
			//修改密码
			modifyPassword(){
				uni.navigateTo({
					url:"./modify_password"
				})
			},
			//前往疫情上报
			toEpidemicReport(){
				uni.navigateTo({
					url:"./farmer/epidemicList/epidemicList"
				})
			},
			//下载
			download(){
				this.disabled = true;
				this.cancel = false;
				if(this.upData.pkgUrl){
				plus.runtime.openURL(this.upData.pkgUrl);
				}
				else if(this.upData.wgtUrl){
					const downloadTask =  uni.downloadFile({
						  url: this.upData.wgtUrl,
						  success: (downloadResult) => {  
							  console.log(downloadResult);
							  if (downloadResult.statusCode === 200) {  
								  plus.runtime.install(downloadResult.tempFilePath, {  
									  force: false  
								  }, ()=>{  
									  console.log('install success...');  
									  this.system.updated = true;
									  plus.runtime.restart();  
								  },(e)=> {  
									  console.log(e)
									  this.progress = 0;
									  uni.showModal({
									  	title:"安装提示",
										content:e.message,
										showCancel:false,
										success: (res) => {
											if(res.confirm){
												this.isShow = false;
											}
										}
									  })
								  });  
							  }  
						  }  
						}); 
					downloadTask.onProgressUpdate((res) => {
						// console.log(res)
					    this.totalBytesExpectedToWrite = this.getFileSize(res.totalBytesExpectedToWrite);//预期需要下载的数据总长度，单位 Bytes
						this.progress = res.progress;//	下载进度百分比
					    // 取消下载任务。
					    if (this.cancel) {
							this.progress = 0;
					        downloadTask.abort();
							console.log('取消了')
					    }
					});
				}
			},
			getFileSize(fileByte) {
			    var fileSizeByte = fileByte;
			    var fileSizeMsg = "";
			    if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB";
			    else if (fileSizeByte == 1048576) fileSizeMsg = "1MB";
			    else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB";
			    else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) fileSizeMsg = "1GB";
			    else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB";
			    else fileSizeMsg = "文件超过1TB";
			    return fileSizeMsg;
			},
			//检查更新
			update(){
				// console.log(plus.runtime.version,plus.runtime.appid);
				plus.runtime.getProperty(plus.runtime.appid,(e)=>{
					this.version = e.version;
					var server = this.confige.webUrl+"/update"; //检查更新地址
					var req = { //升级检测数据  
					    "appid":plus.runtime.appid,  
						"version":this.version
					};  
					uni.request({  
					    url: server,  
					    data: req,
					    success: (res) => {  
							console.log(res);
							
							if(res.data.code==400){
								
								uni.showToast({
									icon:"none",
									title:res.data.message
								})
								return;
							}
							if(res.data.result[0]){
							this.updataContent =res.data.result[0].note;
							}
					       if (res.data.result[0].pkgUrl){
							    this.upData = res.data.result[0];
					            this.upTitle = "大版本更新",
								this.updataContent = res.data.result[0].note;
								this.isShow = true;
					        }
							// 安装 wgt 资源包成功后，必须执行 plus.runtime.restart()，否则新的内容并不会生效。
							else if(res.data.result[0].wgtUrl){
								this.upData = res.data.result[0];
								this.upTitle = "小版本更新",
								this.updataContent = res.data.result[0].note;
								this.isShow = true;
							}
							else {
								this.system.updated = false;
								uni.showToast({
									icon:"none",
									title:"您当前已是最新版本"
								})
							}
					    }  
					})
				});
				 
			},
		
			//清除缓存
			clear(){
				uni.showModal({ 
				    title: "提示",  
				    content:"确定要清除应用的缓存吗",  
				    success: (data) => {  
				        if (data.confirm) { 
						   uni.clearStorage();
				           uni.showToast({
				           	title:"已成功清除"
				           }) 
				        }  
				    }  
				})  
				
			},
			//退出登录
			logout(){
				uni.showModal({
					title:"提示",
					content:"您确定要退出登录吗",
					success: (res) => {
						 if (res.confirm) {
							   uni.request({
								url:this.confige.webUrl+"/logout",
								data:{
								},
								header:{
									'X-Token':this.User.token
								},
								success: (res) => {
									// console.log(res)
								}	
							   })
							   this.User.close();
							   this.User.isConnnect = false;
							   uni.removeStorageSync('isConnnect'+this.User.userInfo.id);
							   uni.removeStorageSync('token');
							   this.User = "";
							   uni.reLaunch({
							   url:'../userLogin/userLogin'
							   })
						    }
							 else if (res.cancel) {
							            console.log('用户点击取消');
							        }
					}
				})
			
				
			},
			//查看我的二维码
			toMyScan(){
				uni.navigateTo({
					url:"./farmer/myScan"
				})
			},
			//邀请员工
			toInviteEmployees(){
				uni.navigateTo({
					url:"./farmer/InviteEmployees"
				})
			},
			//权限划分
			toGrading(){
				uni.navigateTo({
					url:'grading'
				})
			},
			
			//预览头像
			previewHeadImg() {
					var arr = [1];
					arr[0] = this.headImgURL;
				    uni.previewImage({
				            urls: arr,
				            longPressActions: {
				                itemList: ['更换头像', '保存至本地'],
				                success:(data) => {
									console.log(data)
				                switch(data.tapIndex){
								 case 0 :
									console.log(1);
									this.changeImage();
								 case 1:
								 console.log(2);
								  break;
								}
								},
				                fail: function(err) {
				                    console.log(err.errMsg);
				                }
				            }
				        });
				
			},
			//更换头像
			changeImage(){
				uni.chooseImage({
					count:1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						let rotate = 0;
						this.img = res.tempFilePaths[0];
						// console.log(this.img);
						uni.getImageInfo({
							src:res.tempFilePaths[0],
							success: (res) => {
								// console.log(res)
								var or = res.orientation;
								 switch (or) {  
									case 'up': //exif:1 不旋转  
										rotate = 0;  
										break;  
									case 'down': //exif:3 旋转180度  
										rotate = 180;  
										break;  
									case 'right': //exif:6 旋转90度  
										rotate = 90;  
										break;  
									case 'left': //exif:8 旋转270度  
										rotate = 270;  
										break;  
									default:  
										rotate = 0;  
										break;  
								}  
									plus.zip.compressImage({  
										src:this.img,  
										dst: "_doc/uniapp_temp" + '/compressed/' + Math.round(new Date()) + '.jpg',  
										// format: 'jpg',  
										quality:50,  
										width: 'auto',  
										height: 'auto',  
										rotate: rotate,  
									},  
									(event) => {  
										this.imgList = event.target;
										// console.log(this.imgList);
										this.imageUpload(this.imgList)
										uni.showLoading({
											title:"上传中"
										})
									},  
									(error)=> {  
										console.log(error);  
									}); 
							},
							fail: (err) => {
								console.log(err)
							}
							
						})
						
					}
				});
			},
			//图片上传
			imageUpload(FilePaths){
				// console.log(FilePaths)
				//console.log(FilePaths,this.User.userRight.id,this.User.token)
				 uni.uploadFile({
				            url:this.confige.webUrl+"/headPortrait",
				            filePath: FilePaths,
				            name: 'file',
				            formData:{
				                'token':this.User.token,
								'userId':this.User.userInfo.id
				            },
				            success: (uploadFileRes) => {
								console.log(uploadFileRes)
								let img = JSON.parse(uploadFileRes.data)
								console.log(img)
								if(img.code==200){
									setTimeout(()=> {
								    uni.hideLoading();
									// this.headImgURL = img.result[0].url;
									// console.log(this.headImgURL)
									this.User.userInfo.userHead = img.result[0].url;
									uni.downloadFile({
									    url: this.User.userInfo.userHead, //仅为示例，并非真实的资源
									    success: (res) => {
											uni.saveFile({
											     tempFilePath:res.tempFilePath,
											     success:(data)=>{
												 uni.setStorageSync('headImg'+this.User.userInfo.id,data.savedFilePath);
												 this.headImgURL = uni.getStorageSync('headImg'+this.User.userInfo.id);
											     }
											   });
									    }
									});
									// uni.setStorageSync('headImg'+this.User.userInfo.id,this.User.userInfo.userHead);
									uni.showToast({
										title: "更换头像成功！",
										icon: "none"
									})
								}, 1000);
								}
								else{
									uni.showToast({
										title:"上传错误",
										icon:"none"
									})
								}
								
				            },
							fail:(err)=>{
								console.log(err)
							}
				});
			},
		
		
		}
	}
</script>

<style lang="less">
	@import "../../common/colorui/main.css";
	@import "../../common/colorui/icon.css";
	@import "../../common/global.less";
	@import "../../common/seticon.css";
	@import "../../common/animate.css";
	.center{
		display: flex;
		 justify-content: center;
		 align-items: center;
	}
	.sendModel{
		background-color: @uni-bg-color-mask;
		position:fixed;
		 top:0;
		 height:100%;
		 width:100%;
		 z-index: 50;
		 .center
		 }
	.updateModel{
		background-color: #FFFFFF;
		border-radius: 20rpx;
		height: 560rpx;
		width: 620rpx;
		display: flex;
		flex-direction: column;
		.title{
			height: 90rpx;
			.center;
			background-color: #4AC997;
			color: #FFFFFF;
			font-size: 35rpx;
			border-radius:20rpx 20rpx 0rpx 0rpx;
		}
		.box{}
		.content{
			height: 280rpx;
		}
		.scroll{
			height: 280rpx;
			font-size: 30rpx;
			padding: 10rpx;
			width: 98%;
			margin: auto;
		}
		.downSize{
			padding: 2rpx 10rpx;
			font-size: 26rpx;
			color: #9e9e9e;
		}
		.progress{
			height: 35rpx;
			margin: 10rpx;
			.realTime{
				width: 85%;
				height: 35rpx;
				float:left;
				background-color: #ebebeb;
				border-radius:10rpx;
			}
			.real{
				height: 35rpx;
				background-color: #4AC997;
				border-radius:10rpx;
			}
			.percent{
				float: left;
				font-size: 30rpx;
				line-height: 35rpx;
				padding-left: 10rpx;
			}
		}
		.butModel{ 
			display: flex;
			flex-direction: row;
			padding-top: 20rpx;
			}
		.cancelBut{
			height: 65rpx;
			line-height: 65rpx;
			width: 40%;
			font-size: 30rpx;
		}
		}
	page{background-color: #F8F8F8;}
	.bor { border-bottom: 1rpx solid #eaeaea;}
	.top { margin-top: 20rpx;}
	.setListModel{
		background-color: #FFFFFF;
		padding: 20rpx 0rpx;
		display: flex;
		justify-content:flex-end;
		align-items: center;
	}
	.setList{ 
		 width: 92%;
		 }
 .setListLi{
	 background-color: #FFFFFF;
	 display: flex;
	 align-items: center;
	 padding: 25rpx 0rpx 25rpx 15rpx;
	 position:relative;
	 image{ width: 50rpx; height: 50rpx;}
	 text {
		margin-left: 50rpx;
		font-size: 35rpx;
		color: #7c7c7c;
		letter-spacing:10rpx; }
		>view {
		height: 18rpx;
		width:18rpx;
		background-color:#FF504D;
		border-radius: 100%;
		position:absolute;
		right: 0;
		margin-right: 40rpx;
		}
 }
 .head{
	 z-index: 10;
	 position: fixed;
	 top: 0;
	 min-height:450rpx;
	 width: 100%;
 background-image: url(../../static/set/bg.png);
 background-repeat: no-repeat;
 background-size: 100% 100%;
 -moz-background-size: 100% 100%;
  display: flex;
  align-items: center;
 }
 .centent { 
	 display: flex;
	 justify-content: center;
	 align-items: center;}
 .headImg{ 
	 margin-left: 30rpx;
	 margin-top: 30rpx;
	 height: 200rpx;
	 width: 200rpx;
	 border-radius: 100%;
	.centent;
	 >view{
		 // box-shadow: 0rpx 0rpx 100rpx #87ddbb inset;
		.centent;
		width: 140rpx;
		height: 140rpx;
		border-radius: 50%;
		display: inline-block;
		vertical-align: middle;
		overflow: hidden;
		padding: 5rpx;
		background-color: #FFFFFF;
	}
    >view>image {
		 .centent;
		 border-radius:100%;
		 width: 100%;
		 height: 100%;
		 display: block;}
 }
 .hearText{
	 margin:30rpx 0rpx 0rpx 15rpx;
	 color: #FFFFFF;
	 >view:nth-of-type(1){
		 text-align: left;
		 font-size: 40rpx;
		 letter-spacing: 6rpx;
		 margin-bottom: 15rpx;
	 }
	 >view:nth-of-type(2){
		 // text-align: center;
		     display: flex;
			 flex-direction: row;
			 align-items: center;
			 justify-content: center;
			 text{ 
				 padding-left: 15rpx;
				 text-align: center;
				 padding: 5rpx 5rpx 5rpx 0rpx;
				 }
			 width:180rpx;
			 margin: auto;
			 font-size: 28rpx;
			 border: 1rpx solid #FFFFFF;
			 border-radius: 30rpx;
	 }
 }
</style>
